﻿using Aliphant.Mvvm.XEvent.UI;
using Aliphant.UI.Browser.Managers;
using Microsoft.Web.WebView2.Core;

using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Aliphant.UI.Browser.Views
{
    /// <summary>
    /// WebView.xaml 的交互逻辑
    /// </summary>
    public partial class WebView : UserControl
    {
        private bool isLoad = false;
        public string Id { get; set; } = Guid.NewGuid().ToString();


        public string WebTitle
        {
            get { return (string)GetValue(WebTitleProperty); }
            set
            {
                SetValue(WebTitleProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for WebTitle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty WebTitleProperty =
            DependencyProperty.Register("WebTitle", typeof(string), typeof(WebView));



        public WebView()
        {
            InitializeComponent();
            InitializeWebView2();
        }

        private async void InitializeWebView2()
        {
            var userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XDeskTool/WebView2Data");

            var env = await CoreWebView2Environment.CreateAsync(
                browserExecutableFolder: null,
                userDataFolder: userDataFolder
            );
            // 关键：必须在设置 Source 前初始化环境
            await webView.EnsureCoreWebView2Async(env);
        }

        private async Task Load()
        {
            if (!isLoad)
            {
                isLoad = true;
                await OnLoad();
            }
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!isLoad)
            {
                isLoad = true;
                await OnLoad();
            }
        }

        /// <summary>
        /// 初始化WebView
        /// </summary>
        /// <returns></returns>
        private async Task OnLoad()
        {
            if (webView.CoreWebView2 == null)
            {
                await webView.EnsureCoreWebView2Async().ContinueWith(_ =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        if (webView.CoreWebView2 != null)
                        {
                            webView.SourceChanged += WebView_SourceChanged;
                            webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
                        }
                    });
                });

                if (webView.CoreWebView2 != null)
                {
                    webView.CoreWebView2.NewWindowRequested += OnNewWindowRequest;  // 拦截打开新Web窗口请求
                }

            }
        }

        /// <summary>
        /// url更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebView_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs e)
        {
            WebTitle = webView.CoreWebView2.DocumentTitle;
            TabManager.Instance.UpdateInputUrl(webView.CoreWebView2.Source);
        }

        /// <summary>
        /// 新Web窗口请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnNewWindowRequest(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();
            var newView = TabManager.Instance.Create();
            await newView.Load();

            e.NewWindow = newView.webView.CoreWebView2;
            deferral.Complete();
        }

        /// <summary>
        /// 页面加载完成回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CoreWebView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                WebTitle = webView.CoreWebView2.DocumentTitle;
                TabManager.Instance.UpdateInputUrl(webView.CoreWebView2.Source);
            }
        }

        /// <summary>
        /// 关闭网页
        /// </summary>
        public ICommand CloseCommand
        {
            get => new UICommand<object>(obj =>
            {
                TabManager.Instance.Remove(Id);
            });
        }

        /// <summary>
        /// 收藏网页
        /// </summary>
        public ICommand CollectionCommand
        {
            get => new UICommand<object>(obj =>
            {
                //var models = ConfigContainer.Instance.cacheManager.Get<List<NavigateWebModel>>("apps");
                //if (models != null)
                //{
                //    var source = webView.CoreWebView2.Source;
                //    models.Add(new NavigateWebModel
                //    {
                //        Name = this.WebTitle,
                //        ViewName = "webview",
                //        WebUri = source
                //    });
                //    MessageBox.Show("收藏成功");
                //}
                //ConfigContainer.Instance.cacheManager.Update("apps", models);
            });
        }

    }
}
